package org.zjx.app.task;

import lombok.Data;
import org.zjx.app.commnad.ICommand;
import org.zjx.command.entity.Quest;
import org.zjx.command.entity.screen.Address;
import org.zjx.command.entity.screen.Npc;
import org.zjx.command.state.StateManager;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public abstract class Task {
    //任务标题
    protected String title;
    //任务名称
    protected String name;
    //模板
    protected List<String> templates;
    //任务类型
    protected TaskType taskType;
    //执行序号（顺序任务用）
    protected int currentIndex;
    //任务总执行次数（随机任务用）
    protected int totalReps;
    //执行次数
    protected int executeCount;
    //是否完成
    protected boolean completed;

    //领取npc坐标
    protected Npc npc;
    //领取npc对话
    protected List<String> dialogues;

    public Task(String title, String name, TaskType taskType) {
        this.title = title;
        this.name = name;
        this.taskType = taskType;
        this.templates = getTemplates();
        this.completed = false;
        this.currentIndex = 0;
        this.executeCount = 0;
    }


    public Quest containsQuest(List<Quest> quests) {
        if (quests == null || quests.isEmpty()) return null;
        for (Quest quest : quests) {
            if (name.contains(quest.getName())) return quest;
        }
        return null;
    }

    public abstract List<String> getTemplates();

    public abstract ICommand getCommand(StateManager stateManager);

    void complete(Quest quest) {
        if (quest == null || completed || !quest.getName().equals(name)) return;
        if (taskType == TaskType.SEQUENTIAL) {
            currentIndex++;
            if (currentIndex >= templates.size()) {
                completed = true;
            }
        } else if (taskType == TaskType.RANDOM) {
            executeCount++;
            if (executeCount >= totalReps) {
                completed = true;
            }
        }
    }


    //任务中坐标获取
    public static Address parseAddress(String input) {
        // 正则表达式匹配模式：地址名称 + x坐标 + 中英文逗号 + y坐标
        // 支持："江南野外45,78"、"江南野外 45, 78"、"女儿村93，72"、"女儿村93， 72"等格式
        Pattern pattern = Pattern.compile("^(.*?)(\\d+)\\s*[，,]\\s*(\\d+)$");
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            String city = matcher.group(1).trim();  // 获取地址名称并去除前后空格
            int x = Integer.parseInt(matcher.group(2));  // 获取x坐标
            int y = Integer.parseInt(matcher.group(3));  // 获取y坐标

            return new Address(city, x, y);
        } else {
            throw new IllegalArgumentException("输入的地址格式不正确，应为'地址x,y'或'地址x，y'格式，例如：'江南野外45,78'或'女儿村93，72'");
        }
    }
}
